<!--企业签约对话框-->
<template>
	<div class="renter-sign-dialog">
		<a-form ref="form" :model="entity" layout="vertical" :rules="charterContractRules(entity)">
			<a-typography-paragraph strong>
				<blockquote>承租企业</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="8">
					<a-form-item label="承租企业信息：" name="enterPriseId">
						<a-select
							:disabled="isDisabled()"
							v-model:value="entity.enterPriseId"
							show-search
							placeholder="请选择企业"
							allow-clear
							:filter-option="filterOption"
							@change="selectEnterPriseId">
							<a-select-option v-for="item in options.enterpriseList" :key="item" :value="item.id">
								{{ item.enterPriseName }}/{{ item.enterPrisePhone }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<template v-if="entity.enterPriseId">
					<a-col :span="8">
						<a-form-item label="统一社会信用代码：">
							<a-input v-model:value="entity.societyCode" disabled placeholder="请输入社会信用代码" style="flex: 1" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="企业联系人：" name="enterPriseUserId">
							<a-select
								v-model:value="entity.enterPriseUserId"
								placeholder="请选择联系人"
								@change="selectPriseUser"
								:disabled="isDisabled('enterPriseUserId')">
								<a-select-option v-for="item in options.contacts" :key="item.id" :value="item.id">
									{{ [item.linkmanName, item.linkmanPhone, item.linkmanPost].filter(o => o).join('/') }}
								</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="合作周期：" name="enterPriseTeamWorkId">
							<a-select
								:disabled="isDisabled('enterPriseTeamWorkId')"
								v-model:value="entity.enterPriseTeamWorkId"
								placeholder="请选择合作周期"
								@change="selectWorkId">
								<a-select-option v-for="item in options.teamworks" :key="item.id" :value="item.id">
									{{ item.beginTime + '至' + item.endTime }}
								</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="5">
						<!-- 补签 换房不检验 -->
						<a-form-item
							label="费用支付配置："
							name="costPaymentConfigs"
							:rules="[{required: !(supplementaryId || isEnterPriseExchange), message: '请选择费用支付配置'}]">
							<a-button :disabled="isDisabled('续签和补签和换房')" type="primary" block @click="onClickToCostConfig">
								<check-outlined v-if="entity.costPaymentConfigs?.length" />
								<plus-outlined v-else />
							</a-button>
						</a-form-item>
					</a-col>
					<a-col :span="24">
						<a-form-item label="协议优惠方案：" name="discountIds">
							<!-- :disabled="props.id !== ''" -->
							<a-select
								:disabled="isDisabled('enterPriseTeamworkDiscountId')"
								v-model:value="entity.discountIds"
								mode="multiple"
								placeholder="请选择协议优惠方案"
								allow-clear
								@change="selectDiscountId">
								<template v-for="item in options.discount" :key="item.id">
									<a-select-option :value="item.id" :disabled="item.disabled">
										{{ item.discountName }}
										<template v-if="item.id">
											{{
												'[' +
												[
													item.beginTime + '至' + item.endTime,
													rentTypeMap[item.type],
													discountTypeMap[item.discountType] + item.discountScale + '%',
													item.stackable ? '可叠加' : '不可叠加',
													item.feeSubjects.map(o => o.name).join('/')
												]
													.filter(o => o)
													.join('/') +
												']'
											}}
										</template>
									</a-select-option>
								</template>
								<!-- 自定义优惠需要有权限才可以选择 -->
								<template v-if="store.hasPermissions(['mk_contract_charter_zjyhj', 'mk_contract_charter_yjyhj'])">
									<a-select-option value="-1" :option="{discountName: '自定义优惠'}">自定义优惠</a-select-option>
								</template>
							</a-select>
						</a-form-item>
					</a-col>
				</template>
			</a-row>

			<a-typography-paragraph strong class="toolbar-color-blockquote">
				<blockquote>
					房间信息
					<!-- 续租 不展示新增按钮 -->
					<a v-if="!props.reletIds.length" @click="onClickToSelectHouse">
						<plus-circle-outlined />
					</a>
					<template v-if="OccupationRoomsList.length">
						<span v-color="{color: 'danger'}">以下标红房间已被占用,请删除后重新签约</span>
					</template>
					<template v-else-if="conflictRoomList.length">
						<span v-color="{color: 'danger'}">以下标红房间签约的业主合同周期与当前企业合同的周期冲突</span>
					</template>
					<template v-if="props.isEnterPriseExchange">（换房1间）</template>
					<template v-else-if="entity.enterPriseContractHouseRoomFroms?.length">
						（已选{{ entity.enterPriseContractHouseRoomFroms?.length }}间）
					</template>

					<template v-if="props.reletIds.length">
						<a-button small @click="onSubmitBill(2)">重选房间</a-button>
					</template>
				</blockquote>
				<a-input-search
					v-model:value.trim="search"
					enter-button
					allow-clear
					:maxlength="50"
					placeholder="请输入房源地址"
					@search="getTableData"
					style="width: 400px" />
			</a-typography-paragraph>
			<!-- v-if="entity.enterPriseContractHouseRoomFroms?.length" -->
			<a-form-item name="enterPriseContractHouseRoomFroms">
				<a-form-item-rest>
					<vxe-table
						ref="houseInfoTable"
						:data="entity.enterPriseContractHouseRoomFroms"
						v-bind="houseTableOption"
						:row-class-name="rowClassName"
						:cell-style="cellStyle">
						<vxe-column field="houseAddress" min-width="400" title="房源地址" resizable />
						<vxe-column min-width="260" align="right">
							<template #header>
								<a-space>
									<div>租金/底价/优惠价(元/月)</div>
									<a-button v-if="isCustomDiscount" size="small" type="primary" @click="batchModal.show('discountPrice')">批量修改</a-button>
								</a-space>
							</template>
							<template #default="{row}">
								{{ row.price }}
								/
								{{ row.basePrice }}
								/
								<template v-if="isCustomDiscount && store.hasPermissions('mk_contract_charter_zjyhj')">
									<a-input-number
										v-model:value="row.discountPrice"
										:min="0"
										:max="row.price"
										size="small"
										:precision="2"
										:controls="false"
										@blur="
											() => {
												if (!isAllowBasePrice && row.discountPrice < row.basePrice) {
													row.discountPrice = row.basePrice
													message.error('优惠价格不可低于底价，请重新输入')
												}
											}
										"
										style="width: 100px" />
								</template>
								<span v-else v-color="{color: !isAllowBasePrice && row.discountPrice < row.basePrice ? 'red' : 'black'}">
									{{ XEUtils.round(row.discountPrice, 2) }}
								</span>
							</template>
						</vxe-column>
						<vxe-column field="deposit" min-width="220" align="right">
							<template #header>
								<a-space>
									<div>押金/优惠价(元)</div>
									<a-button v-if="isCustomDiscount" size="small" type="primary" @click="batchModal.show('discountDeposit')">批量修改</a-button>
								</a-space>
							</template>
							<template #default="{row}">
								{{ row.depositMonthPrice }}
								/
								<template v-if="isCustomDiscount && store.hasPermissions('mk_contract_charter_yjyhj')">
									<a-input-number
										:disabled="contractDecision.disabledeposit"
										v-model:value="row.discountDeposit"
										@change="discountCalculate"
										:min="0"
										size="small"
										:precision="2"
										:controls="false"
										style="width: 100px" />
								</template>
								<template v-else>{{ XEUtils.round(row.discountDeposit, 2) }}</template>
								<span v-if="entity.depositMonth !== 1">x {{ entity.depositMonth }}</span>
							</template>
						</vxe-column>
						<!-- <vxe-column field="currentFloor" min-width="80px" align="right" title="楼层"></vxe-column> -->
						<vxe-column field="propertyPrice" min-width="150px" align="right" title="" v-if="contractDecision.shiftProperty">
							<template #header>
								物业费(元/月)
								<a-popover placement="bottomLeft">
									<template #content>
										<p v-if="contractDecision.shiftPropertyType === 1">物业费=房型物业费</p>
										<p v-if="contractDecision.shiftPropertyType === 2">物业费=房间面积×物业费单价</p>
									</template>
									<question-circle-outlined :style="{color: 'rgba(0,0,0,0.85)'}" />
								</a-popover>
							</template>
							<template #default="{row, rowIndex}">
								<template v-if="contractDecision.shiftPropertyType === 1">
									{{ row.propertyPrice }}
								</template>
								<template v-if="contractDecision.shiftPropertyType === 2">
									<span>{{row.houseArea}}</span>
									<span> x {{ row.communityPropertyPrice }}</span>
								</template>
							</template>
						</vxe-column>
						<vxe-column field="houseArea" min-width="80px" align="right" title="面积"></vxe-column>
						<vxe-column field="houseRoomTypeName" min-width="150px" align="right" title="房型"></vxe-column>

						<vxe-column title="操作" width="60px" align="center">
							<template #default="{row, rowIndex}">
								<a
									v-if="
										((props.reletId == null && props.resubmitId == null) ||
											(props.supplementaryId && props.resubmitId === null)) &&
										!props.isEnterPriseExchange
									"
									v-color="{color: 'danger'}"
									@click="onClickToRemoveRow(entity.enterPriseContractHouseRoomFroms, rowIndex)">
									<svg-icon icon-class="trash" />
								</a>
							</template>
						</vxe-column>
					</vxe-table>
				</a-form-item-rest>
				<!--实现表单校验失败滚动到此处-->
				<a-input :bordered="false" style="position: absolute" />
			</a-form-item>

			<a-space :size="15" style="margin: 1em 0">
				<div class="d-module-title">
					<b>合同信息</b>
				</div>
				<div>
					<a-typography-text>预计首期租金：</a-typography-text>
					<span v-color="{color: 'primary'}">{{ expectedRent }}</span>
				</div>
				<div>
					<a-typography-text>预计首期押金：</a-typography-text>
					<span v-color="{color: 'primary'}">{{ expectedDeposit }}</span>
				</div>
				<div>
					<a-typography-text>预计其他费用：</a-typography-text>
					<span v-color="{color: 'primary'}">{{ expectedOtherFee }}</span>
				</div>
				<a-popover placement="bottomLeft">
					<template #content>
						<p>首期租金: 根据已选房间对已选房间的首期租金进行求和计算</p>
						<p>首期押金: 根据已选房间对已选房间的首期押金进行求和计算</p>
						<p>其他费用: 根据加收费用添加的费用科目，统计已选费用科目的首期费用总和。</p>
						<a-divider />
						<p v-color="{color: 'primary'}">首期租金: ∑所有房间租金优惠价（元/月）× 租金一次性支付月数（付几）</p>
						<p v-color="{color: 'primary'}">首期押金: ∑所有房间押金优惠价（元/月）× 押金一次性支付月数（押几）</p>
						<p v-color="{color: 'primary'}">预计其他费用: ∑加收费用的预计首期费用</p>
					</template>
					<template #title>
						<span v-color="{color: 'primary'}" class="popover-title-size">说明</span>
					</template>
					<question-circle-outlined :style="{color: 'rgba(0,0,0,0.85)'}" />
				</a-popover>
			</a-space>
			<a-row :gutter="12">
				<a-col :span="6">
					<a-form-item
						label="成交方式/合同编号："
						name="contractNo"
						:rules="[{required: contractDecision.contractNo, message: '请输入合同编号'}]">
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select v-model:value="entity.signType" disabled :options="signTypeList" style="width: 80px" />
							</a-form-item-rest>
							<!-- :disabled="isDisabled('续签和补签和换房')" -->
							<a-input v-model:value.trim="entity.contractNo" placeholder="请输入合同编号" style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item name="beginTime">
						<template #label>
							合同周期：
							<span v-if="entity.enterPriseTeamWorkId">
								（企业合作周期：{{ currentTeamwork.beginTime + '至' + currentTeamwork.endTime }}）
							</span>
						</template>
						<a-input-group compact class="display-flex">
							<a-range-picker
								:value="[entity.beginTime, entity.endTime]"
								:value-format="DATE_FORMAT.DATE"
								:disabled-date="disabledDate"
								:disabled="[props.reletId !== null || props.isEnterPriseExchange, isDisabled('supplementaryId') || false]"
								style="flex: 1"
								@change="onDateChange"
								@calendarChange="changeDate"></a-range-picker>
							<a-form-item-rest>
								<a-radio-group
									class="month-quick-radio-group"
									:disabled="isDisabled('supplementaryId')"
									v-model:value="entity.leasePeriod"
									button-style="solid"
									@change="quickSelectDate">
									<a-radio-button :value="6">半年</a-radio-button>
									<a-radio-button :value="12">1年</a-radio-button>
									<a-radio-button :value="24">2年</a-radio-button>
									<a-radio-button :value="36">3年</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="月租金：" name="price">
						<a-input-number v-model:value="entity.price" :min="0" :precision="2" disabled placeholder="请输入租金" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="押金：" name="deposit">
						<a-input-number v-model:value="entity.deposit" :min="0" :precision="2" disabled placeholder="请输入押金" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="付款方式：">
						<a-input-group compact class="display-flex">
							<a-select
								:disabled="isDisabled('续签和补签和换房')"
								v-model:value="entity.depositMonth"
								:options="mortgageMonthList"
								placeholder="请选择"
								style="flex: 1"
								@change="discountCalculate()" />
							<a-select
								:disabled="isDisabled('续签和补签和换房')"
								v-model:value="entity.periodMonth"
								:options="periodMonthList"
								placeholder="请选择"
								style="flex: 1" />
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="收租日设置：" name="payPatternValue">
						<a-input-group compact class="display-flex">
							<template v-if="entity.payPattern == 1">
								<a-input-number
									:disabled="isDisabled('续签和补签和换房')"
									v-model:value="entity.payPatternValue"
									prefix="提前"
									:min="0"
									:precision="0"
									style="flex: 1; display: flex" />
							</template>
							<template v-else>
								<a-input-number
									:disabled="isDisabled('续签和补签和换房')"
									v-model:value="entity.payPatternValue"
									prefix="固定"
									:min="1"
									:max="31"
									:precision="0"
									style="flex: 1; display: flex" />
							</template>
							<a-form-item-rest>
								<a-select
									:disabled="isDisabled('续签和补签和换房')"
									v-model:value="entity.payPattern"
									:options="paymentMethodList"
									style="width: 200px"
									@change="entity.payPatternValue = null" />
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="账单生成规则：">
						<a-select
							:disabled="isDisabled('续签和补签和换房')"
							v-model:value="entity.cycleType"
							:options="moonList"
							placeholder="请选择账单生成规则" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item label="合同附件：">
						<a-button type="primary" block @click="visibles.attachment = true">
							<check-outlined v-if="entity.attachmentIds?.length" />
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item
						v-if="!props.resubmitId"
						label="物业交割单："
						name="enterPriseContractHouseRoomFroms"
						:rules="[{required: contractDecision.delivery, message: '请输入物业交割单'}]">
						<a-button
							:disabled="!entity.enterPriseContractHouseRoomFroms?.length || entity.signType === 2"
							type="primary"
							block
							@click="openDeliveryNote">
							<check-outlined v-if="deliveryNoteList?.length" />
							<plus-outlined v-else />
						</a-button>
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item label="补充说明：" name="addExplanation">
						<a-textarea
							v-model:value.trim="entity.addExplanation"
							placeholder="请输入补充说明"
							:rows="4"
							show-count
							:maxlength="200" />
					</a-form-item>
				</a-col>
			</a-row>
			<!--
			<a-typography-paragraph strong>
				<blockquote>
					费用支付配置
					<a @click="onClickToCostConfig">
						<setting-outlined />
					</a>
				</blockquote>
			</a-typography-paragraph>
			<a-typography-paragraph style="margin-bottom: 2em" /> -->

			<a-typography-paragraph strong>
				<blockquote>
					加收费用
					<a @click="onClickToAddOtherBill">
						<plus-circle-outlined />
					</a>
				</blockquote>
			</a-typography-paragraph>
			<a-form-item v-if="entity.otherExpenses?.length" name="otherExpenses" class="add-expected-other-fee">
				<a-form-item-rest>
					<vxe-table ref="otherBillTable" :data="entity.otherExpenses" v-bind="otherBillTableOption">
						<vxe-column min-width="150px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								费用科目
							</template>
							<template #default="{row, rowIndex}">
								<!-- <a-select v-model:value="row.feeSubjectId" :bordered="false" :options="options.feeSubjects" show-search option-filter-prop="name" :field-names="{label: 'name', value: 'id', options: 'metaList'}" placeholder="请选择费用科目" /> -->
								<a-select
									v-model:value="row.feeSubjectId"
									:disabled="(row.disabled && entity.signType === 4) || row.Feedisabled"
									:bordered="false"
									:options="row.isNew ? options.useFeeSubjects : options.feeSubjects"
									@change="(value: string) => feeSubjectChange(value, row)"
									show-search
									option-filter-prop="name"
									:field-names="{label: 'name', value: 'id', options: 'metaList'}"
									placeholder="请选择费用科目" />
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								付款方式
							</template>
							<template #default="{row, rowIndex}">
								<!-- <a-select v-model:value="row.periodMonth" :bordered="false" :options="periodMonthOptions" placeholder="请选择付款方式" /> -->
								<a-select
									v-model:value="row.periodMonth"
									:bordered="false"
									:disabled="row.disabled"
									:options="periodMonthOptions"
									placeholder="请选择付款方式" />
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center">
							<template #header>
								<span v-color="{color: 'danger'}">*</span>
								金额
							</template>
							<template #default="{row, rowIndex}">
								<span v-if="row.Feedisabled">-</span>
								<a-space v-else style="flex-wrap: nowrap">
									<a-input-number
										v-model:value="row.price"
										:bordered="false"
										:controls="false"
										:min="0"
										:precision="2"
										placeholder="请输入金额"
									/>
									<template v-if="[3,6,12,100].includes(row.periodMonth)">
										<span>x</span>
										<count-month :row="row" :entity="entity"/>
									</template>
								</a-space>
							</template>
						</vxe-column>
						<vxe-column min-width="150px" align="center">
							<template #header>
								<a-space size="small">
									<span>预期首期费用</span>
									<a-popover>
										<template #content>预期首期费用 = 金额 x 房间数量</template>
										<question-circle-outlined :style="{color: 'rgba(0,0,0,0.85)'}" />
									</a-popover>
								</a-space>
							</template>
							<template #default="{row}">
								<div class="t-l">{{ toFixedTwo(countSignOtherFee(row, 1)) }}</div>
							</template>
						</vxe-column>
						<vxe-column title="操作" width="60px" align="center">
							<template #default="{row, rowIndex}">
								<a
									v-color="{color: 'danger'}"
									v-if="!row.Feedisabled"
									@click="onClickToRemoveRow(entity.otherExpenses, rowIndex)">
									<svg-icon icon-class="trash" />
								</a>
							</template>
						</vxe-column>
					</vxe-table>
				</a-form-item-rest>
				<!--实现表单校验失败滚动到此处-->
				<a-input :bordered="false" style="position: absolute" disabled />
			</a-form-item>
			<a-typography-paragraph v-else style="margin-bottom: 2em" />

			<a-typography-paragraph strong>
				<blockquote>签约信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="8">
					<a-form-item label="签约人/维护人：" name="signEmpId">
						<dept-emp-select
							:disabled="isDisabled('续签和补签和换房')"
							v-model:dept-id="entity.signDeptId"
							v-model:emp-id="entity.signEmpId"
							@change="form?.validate('signEmpId')" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="签约时间：" name="signTime">
						<a-date-picker v-model:value="entity.signTime" placeholder="请选择签约日期" :value-format="DATE_FORMAT.DATE" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>

		<teleport v-if="visibles.footer" to=".signing-dialog .ant-modal-footer">
			<a-button type="primary" :disabled="disables.save" :loading="loadings.save" @click="submit">保存并核对账单</a-button>
		</teleport>
		<!-- <a-modal v-model:open="open" title="提示" ok-text="确认" cancel-text="取消" @ok="visibles.billPreview = true" >
			<div>以下房间签约的业主合同周期与当前企业合同的周期冲突,您确定继续操作吗?</div>
			<p>冲突房源:</p>
			<template v-for="(item, index) in conflictRoomNameList" :key="item.id">
				<div v-if="index < 3">{{ item.houseAddress }}</div>
				<div v-if="index === 3">...</div>
			</template>
		</a-modal> -->
		<!-- 选择房间 -->
		<select-house
			v-model:visible="visibles.selectHouse"
			:validateConfig="contractDecision"
			:room-selected="entity.enterPriseContractHouseRoomFroms"
			@success="onSubmitSuccess" />
		<!-- 附件上传 -->
		<file-upload-dialog v-model:visible="visibles.attachment" v-model:files="attachments" />
		<!-- 证件上传 -->
		<certificate-upload-dialog v-model:visible="visibles.certificate" :imgs="renter" />
		<!-- 费用配置 -->
		<cost-config
			v-model:visible="visibles.costConfig"
			:cost="(entity.costPaymentConfigs as [])"
			@success="onSubmitCost"
			:id="props?.reletId || props?.resubmitId" />
		<!-- 账单预览 -->
		<enter-bill-preview-dialog
			v-model:visible="visibles.billPreview"
			:contract="entity"
			:is-custom-discount="isCustomDiscount"
			@success="onSubmitBill" />
		<!-- 物业交割单 -->
		<delivery-note
			:isCharterSign="true"
			:enterPriseContractHouseRoomFroms="entity.enterPriseContractHouseRoomFroms"
			v-model:visible="visibles.deliveryNote"
			@success="getDelivery" />
		<conflict-model v-model:visible="open" :conflictRoomNameList="conflictRoomNameList" @success="visibles.billPreview = true" />
		<!-- 批量修改优惠价 -->
		<Modal v-model:visible="batchModal.visible" title="批量修改" :width="350" @ok="batchModal.ok">
			<a-space>
				<span>批量修改{{batchModal.name}}优惠价：</span>
				<a-input-number
					v-model:value="batchModal.value"
					@pressEnter="batchModal.ok"
					style="width: 150px"
					:min="0"
					placeholder="请输入"
					:precision="2"
					:controls="false"
				/>
			</a-space>
			<template #footer>
				<a-button key="submit" type="primary" @click="batchModal.ok" :disabled="!batchModal.value">确定</a-button>
			</template>
		</Modal>
	</div>
</template>

<script lang="ts" setup>
	import dayjs, {Dayjs} from 'dayjs'
	import isBetween from 'dayjs/plugin/isBetween'
	import {useStore} from '@/store'
	import XEUtils from 'xe-utils'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {computed, createVNode, onMounted, reactive, ref, watch, watchEffect} from 'vue'
	import {moonList, mortgageMonthList, paymentMethodList, periodMonthList, periodMonthOptions, signTypeList} from '@/utils'
	import {CheckOutlined, PlusCircleOutlined, PlusOutlined, QuestionCircleOutlined, ExclamationCircleOutlined} from '@ant-design/icons-vue'
	import CertificateUploadDialog from '@/components/common/certificate-upload-dialog.vue'
	import {Img} from 'yuxin-base/src/types'
	import DATE_FORMAT, {nowDate} from 'yuxin-base/src/utils/date'
	import {CERTIFICATION_MAP, DIC_LABEL_MAP, DIC_PID_MAP, DIC_TAG_MAP} from 'yuxin-base/src/constant'
	import {VxeTableInstance, VxeTableProps, VxeTablePropTypes} from 'vxe-table'
	import {FormInstance, message, Modal} from 'ant-design-vue'
	import {charterContractRules} from '@/rules/contract'
	import FileUploadDialog from '@/components/common/file-upload-dialog.vue'
	import {getEnterPriseLibraryListAll, getHouseDeliveryGetNoe, getPeriodTimes} from '@/api/contract'
	import EnterBillPreviewDialog from '@/components/contract/add-charter/enter-bill-preview-dialog.vue'
	import {CharterContract, defaultRenterContract, RenterContract, RenterInfo} from '@/interface/contract'
	import SelectHouse from '@/components/contract/add-charter/select-house.vue'
	import CostConfig from '@/components/contract/add-charter/cost-config.vue'
	import billApi from '@/api/bill-api'
	import {getDispose, getEnterContractDetails, validateHouseStatus, searchRoomCostDetail} from '@/api/charter-contract'
	import fileApi from 'yuxin-base/src/api/file-api'
	import DeliveryNote from '@/components/contract/add-tenant-contract-dialog/delivery-note.vue'
	import ConflictModel from '@/components/contract/add-charter/conflict-modal.vue'
	import {discountTypeMap, rentTypeMap} from '@/constant/enterprise-customers'
	import CountMonth from './count-month'

	dayjs.extend(isBetween)

	const store = useStore()

	const props = withDefaults(
		defineProps<{
			visible: boolean
			contract?: RenterContract
			id?: string
			reletId?: any
			reletIds?: any
			resubmitId?: any
			supplementaryId?: any
			/** 是否企业合同换房 */
			isEnterPriseExchange: boolean
		}>(),
		{
			contract: {
				// @ts-ignore成交方式【1-新签,2-续签,3-转租,4-换房】，默认新签
				signType: 1
			},
			id: '',
			reletId: null,
			reletIds: [],
			resubmitId: null,
			supplementaryId: null,
			isEnterPriseExchange: false
		}
	)

	const loadings = reactive({
		save: false,
		search: false
	})

	const disables = reactive({
		save: false
	})

	const visibles = reactive({
		footer: false,
		selectHouse: false,
		attachment: false,
		certificate: false,
		costConfig: false,
		billPreview: false,
		beginData: '',
		deliveryNote: false
	})
	const leasePeriod = ref(0)

	const emits = defineEmits(['update:visible', 'success'])
	const onCancel = () => {
		attachments.value = []
		entity.beginTime = null
		entity.endTime = null
		reset()
		emits('update:visible', false)
	}

	// 当前时间
	const presentTime = nowDate()

	const search = ref('')

	// 表单内容
	const form = ref<FormInstance>()
	// 租客信息
	const renter = ref<RenterInfo>({})
	// 合同附件
	const attachments = ref<Img[]>([])
	// 合同信息
	const entity = reactive<CharterContract>(defaultRenterContract())
	// 租客原始信息
	const originRenterInfo = ref<RenterInfo>({})

	const oldOnterPriseTeamworkDiscountId = ref()

	// 打开物业交割单
	const openDeliveryNote = () => {
		// houseInfoWithDelivery.value = row
		visibles.deliveryNote = true
	}
	const deliveryNoteList = ref<any>([])

	// 确认完物业交割单的回调
	const getDelivery = delivery => {
		entity.enterPriseContractHouseRoomFroms = delivery
		deliveryNoteList.value = delivery

		houseInfoTable.value?.reloadData(entity.enterPriseContractHouseRoomFroms)
	}

	// 当前合作周期
	const currentTeamwork = computed(() => options.teamworks.find(o => o.id === entity.enterPriseTeamWorkId) || {})

	// 是否允许低于最低价格
	const isAllowBasePrice = ref(true)

	const oldHouseList = ref(0)

	const supplementaryBeginTime = ref(dayjs().format(DATE_FORMAT.DATE))

	const exchangeId = ref('')
	//周期冲突对话框
	const open = ref<boolean>(false)
	//冲突房源名称
	const conflictRoomNameList = ref<any>([])

	/** 决策合同设置 */
	const contractDecision = ref<any>({
		// 物业交割单
		delivery: false,
		// 合同编号
		contractNo: false,

		disabledeposit: false,
		shiftProperty: false,
		shiftPropertyType: [],
		depositType: []
	})

	// 原合同时间
	const oldDate = ref<any>({
		beginTime: null,
		endTime: null
	})

	const disabledDate = (current: Dayjs) => {
		// 表示正常
		let beginTime = currentTeamwork.value.beginTime
		let endTime = currentTeamwork.value.endTime
		if (props.reletId) {
			// 表示续租
			const reletBeginTime = visibles.beginData
			if (reletBeginTime || endTime) {
				return current.isBefore(beginTime, 'day') || current.isAfter(endTime, 'day')
			}
		} else if (props.supplementaryId) {
			return current.isBefore(oldDate.value.beginTime, 'day') || current.isAfter(oldDate.value.endTime, 'day')
		} else {
			if (beginTime || endTime) {
				return current.isBefore(beginTime, 'day') || current.isAfter(endTime, 'day')
			}
		}
	}

	/**
	 * 计算合同周期月数
	 */
	watch(
		() => [entity.beginTime, entity.endTime],
		() => {
			if (entity.beginTime && entity.endTime) {
				const endTime = dayjs(entity.endTime).add(1, 'day')

				let months = endTime.diff(entity.beginTime, 'month', true)

				entity.leasePeriod = XEUtils.toInteger(months)
				leasePeriod.value = entity.leasePeriod
				setCellStyle()
			}
		}
	)
	// 计算押金
	watch(
		() => [entity.depositMonth, entity.enterPriseContractHouseRoomFroms],
		() => {
			entity.price = XEUtils.sum(entity.enterPriseContractHouseRoomFroms, 'discountPrice')
			entity.deposit = XEUtils.sum(entity.enterPriseContractHouseRoomFroms, 'deposit')
		},
		{
			deep: true
		}
	)
	const canceled = ref(true)
	const init = () => {
		// 续租逻辑
		if (canceled.value && props.contract?.signType === 2) {
			emits('update:visible', false)
			billApi.unclearedDeposit(props.contract?.contractId as string).then(({data = []}) => {
				if (data.length > 0) {
					message.error('原合同押金未结清，不能进行续租操作')
				} else {
					emits('update:visible', true)
					canceled.value = false
				}
			})

			return
		}

		getDisc()

		getContractDecision()

		const contract = props.contract || {}

		let renterInfo = contract.renterInfo || {}

		if (contract.otherExpenses && XEUtils.isString(contract.otherExpenses)) {
			try {
				contract.otherExpenses = JSON.parse(contract.otherExpenses || '[]')
			} catch (e) {
				contract.otherExpenses = []
			}
		}

		// @ts-ignore，过滤掉空值
		renterInfo = XEUtils.pick(renterInfo, v => v)
		originRenterInfo.value = renterInfo

		delete contract.renterInfo

		if (XEUtils.isString(renterInfo.interest) && XEUtils.trim(renterInfo.interest)) {
			renterInfo.interest = renterInfo.interest.split('/')
		}

		XEUtils.merge(entity, defaultRenterContract(), contract, {
			// contractId: null,
			contractNo: null,
			signEmpId: store.currentUser.empId,
			signDeptId: store.currentUser.deptId,
			signTime: nowDate(),
			// 包租合同自定义
			enterPriseId: null,
			enterPriseTeamWorkId: null,
			// enterPriseTeamworkDiscountId: null,
			discountIds: [],
			societyCode: null,
			linkmanPhone: null,
			enterPriseContractHouseRoomFroms: [],
			leasePeriod: 6,
			endTime: dayjs().add(6, 'month').add(-1, 'day').format(DATE_FORMAT.DATE),
			costPaymentConfigs: []
		})

		// 换房非重新提交删除id
		if (props.isEnterPriseExchange && !props.resubmitId) {
			entity.id = ''
		}
	}

	onMounted(() => {
		visibles.footer = true
		init()
		getEnterPriseLibraryListAll({}).then(({data}) => {
			options.enterpriseList = data
			if (props.id !== '') {
				enterpriseInformation(data)
			}

			// 如果是企业换房 企业合同id取contract.
			if (props.isEnterPriseExchange && props.contract.enterPriseContractId) {
				exchangeId.value = props.contract.enterPriseContractId

				if (!props.resubmitId) {
					// entity.enterPriseContractHouseRoomFroms = props.contract.enterPriseContractHouseRoomFroms
					onSubmitSuccess(props.contract.enterPriseContractHouseRoomFroms)
				}

				// 前置接口无法拿到签约配置的字段 通过这个接口获取合并进去房源中
				searchRoomCostDetail({
					ids: [props.contract.houseId],
					houseType: 0,
					current: 1,
					size: 1000
				}).then(roomRes => {
					onSubmitSuccess(roomRes.data?.records || [])
				})
			}

			if (props.reletId || props.resubmitId || props.supplementaryId || props.isEnterPriseExchange) {
				contractDetails()
				getDisposeF()
			}
			if (props.reletId) {
				entity.sourceId = props.reletId
				let arr = props.reletIds.map(i => i.enterPriseContractId)
				arr = [...new Set(arr)]
				entity.ids = arr
				console.log('🚀 ~ file: charter-sign.vue:873 ~ getEnterPriseLibraryListAll ~ entity.ids :', entity.ids)
				// 如果不是批量续 直接把reletId塞进去
				if (!props.reletIds.length) {
					entity.ids = [props.reletId]
				}
			}
			if (props.resubmitId) {
				attachmentF()
			}
			// 包租合同子合同换房的时候需要用原合同里面的id去回显附件
			if (exchangeId.value) {
				attachmentF()
			}
		})
		entity.cycleType = 1
	})

	const reset = () => {
		XEUtils.assign(entity, defaultRenterContract(), {
			contractId: null,
			contractNo: null,
			signEmpId: store.currentUser.empId,
			signDeptId: store.currentUser.deptId,
			signTime: nowDate(),
			// 包租合同自定义
			enterPriseId: null,
			enterPriseTeamWorkId: null,
			// enterPriseTeamworkDiscountId: null,
			discountIds: [],
			societyCode: null,
			linkmanPhone: null,
			enterPriseContractHouseRoomFroms: [],
			leasePeriod: 6,
			endTime: dayjs().add(6, 'month').add(-1, 'day').format(DATE_FORMAT.DATE),
			costPaymentConfigs: []
		})
	}

	const options = reactive<any>({
		// 客户来源
		sources: [],
		// 爱好
		hobbies: [],
		// 重点人群
		keyGroups: [],
		// 费用科目
		feeSubjects: [],
		// 已生效的费用科目
		useFeeSubjects: [],
		// 证件类型
		certificateTypes: Object.keys(CERTIFICATION_MAP).map(key => ({
			label: CERTIFICATION_MAP[key],
			value: Number(key)
		})),
		// 企业列表
		enterpriseList: [],
		// 周期
		teamworks: [],
		// 折扣 协议
		discount: [],
		// 承租人联系人信息
		contacts: [],
		HOUSE_SETTING: []
	})
	const validateFee = (contractDecision, houseDetail) => {
		const errorList = []
		const {communityPropertyPrice, propertyPrice, depositPrice} = houseDetail

		const validatePorperty = contractDecision.value.shiftProperty && contractDecision.value.shiftPropertyType === 1
		const validateDeposit = contractDecision.value.disabledeposit
		const validatePorpertyByArea = contractDecision.value.shiftProperty && contractDecision.value.shiftPropertyType === 2
		if (validatePorperty && !propertyPrice) {
			errorList.push({name: '房型物业费'})
		}
		if (validatePorpertyByArea && !communityPropertyPrice) {
			errorList.push({name: '物业费单价'})
		}
		if (validateDeposit && !depositPrice) {
			errorList.push({name: '房型押金'})
		}
		const nameStr = errorList.map(e => e.name).join('、')
		errorList.length && message.error(`房源：${houseDetail.address}未配置${nameStr}，无法操作，请先编辑房源进行配置`)
		return !errorList.length
	}
	const handleSetPropertyFee = () => {
		const shouldPushFees = contractDecision.value.shiftProperty
		const price = entity.enterPriseContractHouseRoomFroms.reduce((acc, cur) => {
			console.log(acc, cur)
			const {propertyPrice, communityPropertyPrice, houseArea} = cur
			const shiftPropertyByRoom = contractDecision.value.shiftPropertyType === 1
			cur.currentProperty = shiftPropertyByRoom ? propertyPrice : communityPropertyPrice * houseArea
			acc += cur.currentProperty
			return acc
		}, 0)
		shouldPushFees &&
			settingApi.getDicListByPidAll(DIC_PID_MAP['FEESUBJECT@SERVICE']).then(({data}) => {
				const current = data.find(e => e.tag === 'HOUSE_PROPERTY_FEE') || {}
				const shouldPush = !entity.otherExpenses.some(e => e.tag === 'HOUSE_PROPERTY_FEE' || e.feeSubjectId === current.id)
				if (shouldPush) {
					entity.otherExpenses.push({
						feeSubjectId: current.id,
						tag: current.tag,
						periodMonth: null,
						price,
						Feedisabled: true
					})
					setTimeout(() => {
						// 为了显示出物业费文案，需要塞一个禁用的物业费选项
						const service = options.useFeeSubjects.find(v => v.label === 'FEESUBJECT@SERVICE')
						if (!service) return
						const property = service.metaList.find(v => v.tag === 'HOUSE_PROPERTY_FEE')
						if (!property) {
							service.metaList.push({...current, disabled: true})
						}
					}, 1000)
				} else {
					entity.otherExpenses.forEach(e => {
						if (e.tag === 'HOUSE_PROPERTY_FEE' || e.feeSubjectId === current.id) {
							e.Feedisabled = true
							e.price = price
						}
					})
				}
			})
	}
	// 获取字典
	const getDisc = async () => {
		settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@HOBBY']).then(({data}) => (options.hobbies = data))
		settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@KEY_GROUPS']).then(({data}) => (options.keyGroups = data))
		settingApi.getDicListByPid(DIC_PID_MAP['CUSTOMER@CHANNELSOURCE']).then(({data}) => (options.sources = data))
		// 82308字典修改
		settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT'], {isUse: null}).then(({data}) => (options.feeSubjects = data))
		settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT'], {isUse: 1}).then(({data}) => (options.useFeeSubjects = data))
	}

	const filterOption = (input: string, option: any) => {
		console.log('🚀 ~ file: charter-sign.vue:1007 ~ filterOption ~ option:', option)
		return option.key?.enterPriseName?.toLowerCase().indexOf(input.toLowerCase()) >= 0
	}

	// 选择企业
	const selectEnterPriseId = (value: string) => {
		// console.log(value)
		const enterPrise = options.enterpriseList.find(e => e.id === value)

		// 回显各个字段
		entity.societyCode = enterPrise.societyCode
		// console.log(enterPrise, 'enterPrise')
		entity.renterInfo.name = enterPrise.linkmanName
		entity.renterInfo.phone = enterPrise.linkmanPhone

		entity.renterInfo.identityCard = enterPrise.linkmanIdCard
		entity.renterInfo.employer = enterPrise.enterPriseName

		options.contacts = enterPrise.contacts || []
		options.teamworks = enterPrise.teamworks || []

		// 折扣id和周期id 最优在最外层
		entity.enterPriseTeamWorkId = enterPrise.enterPriseTeamWorkId
		selectWorkId(entity.enterPriseTeamWorkId)

		entity.enterPriseUserId = null
		selectPriseUser()
	}
	const selectWorkId = (value: any) => {
		if (!value) return
		// offerContent.value = []
		const teamwork = options.teamworks.find(e => e.id === value) || {}

		options.discount = teamwork.discounts || []
		entity.discountIds = []

		checkData()
		selectDiscountId([])
	}

	// 当前是否为自定义优惠
	const isCustomDiscount = ref<boolean>(false)

	const selectDiscountId = (values: string[]) => {
		isCustomDiscount.value = values.includes('-1')

		// 所有优惠禁用状态
		options.discount.forEach(o => (o.disabled = isCustomDiscount.value))

		// 选择了自定义优惠
		if (isCustomDiscount.value) {
			// 移除所有已选优惠
			entity.discountIds = ['-1']
		} else if (values.length) {
			// 是否选择了可叠加优惠
			const stackable = options.discount.some(o => values.includes(o.id) && o.stackable)

			// 禁用相反的优惠
			options.discount.forEach(o => (o.disabled = stackable ? !o.stackable : !values.includes(o.id)))
		}

		discountCalculate()
	}

	const getTableData = () => {
		houseInfoTable.value?.reloadData(entity.enterPriseContractHouseRoomFroms.filter((e: any) => e.address.includes(search.value)))
	}
	//修改房态时间冲突时颜色
	const rowClassName: VxeTablePropTypes.RowClassName<any> = ({row, rowIndex}) => {
		if (dayjs(entity.beginTime).isBefore(row.minDate, 'day') || dayjs(entity.endTime).isAfter(row.maxDate, 'day')) {
			return 'row-red'
		}
		return null
	}
	const conflictRoomList = ref<any>([])
	const ownerContractRoom = ref<any>([])
	const getHouseDate = () => {
		const houseIdList = entity.enterPriseContractHouseRoomFroms.map(o => o.id)
		getPeriodTimes(houseIdList).then(res => {
			ownerContractRoom.value = res.data
			setCellStyle()
		})
	}
	const setCellStyle = () => {
		conflictRoomList.value = []
		if (ownerContractRoom.value && ownerContractRoom.value.length) {
			ownerContractRoom.value.forEach(o => {
				if (dayjs(o.minDate).isAfter(entity.beginTime) || dayjs(entity.endTime).isAfter(o.maxDate)) {
					conflictRoomList.value.push(o.houseId)
				}
			})
		}
	}
	/**
	 * 合作周期是否和合同周期冲突 开始日期为合作周期开始日
	 */
	const intervalDay = ref(0)

	const checkData = () => {
		let beginTime = currentTeamwork.value.beginTime
		let endTime = currentTeamwork.value.endTime
		if (
			(entity.beginTime as string) < beginTime ||
			(entity.beginTime as string) > endTime ||
			(entity.endTime as string) < beginTime ||
			(entity.endTime as string) > endTime
		) {
			entity.beginTime = null
			entity.endTime = null
			entity.leasePeriod = null
		}
		intervalDay.value = dayjs(endTime).diff(beginTime, 'month')
		if (intervalDay.value >= 6) {
			// 默认半年
			entity.beginTime = beginTime
			entity.endTime = dayjs(entity.beginTime)
				.add(entity.leasePeriod || 6, 'month')
				.add(-1, 'day')
				.format(DATE_FORMAT.DATE)
			entity.leasePeriod = 6
		} else {
			entity.leasePeriod = intervalDay.value || 6
			entity.beginTime = beginTime
			entity.endTime = endTime
		}
	}

	const onClickToSelectHouse = () => {
		if (props.resubmitId) return message.error('重新提交不允许变更房间')
		if (props.reletId) return message.error('续租不允许变更房间')
		if (props.isEnterPriseExchange) return message.error('换房不允许变更房间')

		visibles.selectHouse = true
	}

	const onClickToCostConfig = () => {
		visibles.costConfig = true
	}

	// 房间
	const houseInfoTable = ref<VxeTableInstance>()
	const houseTableOption = reactive<VxeTableProps>({
		size: 'small',
		maxHeight: 300,
		border: true,
		resizable: true,
		rowConfig: {
			isHover: true,
			isCurrent: true
		},
		scrollY: {
			gt: 20,
			enabled: true
		}
	})
	const cellStyle = ({row}) => {
		if (OccupationRoomsList.value.includes(row.id)) {
			return {
				color: 'red'
			}
		}
		if (conflictRoomList.value.includes(row.id)) {
			return {
				color: 'red'
			}
		}
	}

	// 其它费用
	const otherBillTable = ref<VxeTableInstance>()
	const otherBillTableOption = reactive<VxeTableProps>({
		size: 'mini',
		maxHeight: 200,
		border: true,
		cellStyle: {padding: 0},
		rowClassName: 'edit-table-row'
	})

	const OccupationRoomsList = ref<string[]>([])

	// 添加其它费用
	const onClickToAddOtherBill = () => {
		entity.otherExpenses?.push({
			isNew: true
		})
		otherBillTable.value?.reloadData(entity.otherExpenses as [])
	}
	/** 换房手续费 转租手续费 */
	const targetFeeTagList = ['EXCHANGE_PROCEDURE_FEE', 'SUBLEASE_PROCEDURE_FEE']
	/** 加收费用 费用科目 change事件 */
	const feeSubjectChange = (value: string, row: any) => {
		let target: any = {}
		options.feeSubjects.forEach(item => {
			const obj = item.metaList.find(v => v.id === value)
			if (obj) {
				target = item
			}
		})
		if (target.label === 'FEESUBJECT@DEPOSIT') {
			// 付款方式 为 一次性付清 且 不可以修改
			row.periodMonth = 99
			row.disabled = true
		} else {
			row.disabled = false
			if (row.periodMonth === 99) {
				delete row.periodMonth
			}
		}
	}

	// 需要被禁用的费用科目大类集合
	// const targetFeeDisabledList = ['FEESUBJECT@DEPOSIT', 'FEESUBJECT@PROCEDURE']
	// 判断是否 押金大类 手续费大类
	const isFeeSubject = (list: any[], tId: string) => {
		let res = false
		list.forEach(item => {
			if (item.label === 'FEESUBJECT@DEPOSIT') {
				res = Boolean(item.metaList.find(v => v.id === tId))
			}
		})
		return res
	}
	// otherExpenses出参只有费用科目id字段 便利判断是否属于押金大类 或 手续费大类
	watchEffect(() => {
		entity.otherExpenses?.forEach(v => {
			if (isFeeSubject(options.feeSubjects, v.feeSubjectId)) {
				v.disabled = true
			}
		})

		// 附件列表
		entity.attachmentIds = attachments.value.map(o => o.id) as []
	})

	const onClickToRemoveRow = (array: any[], index: number) => {
		Modal.confirm({
			title: '系统提示',
			content: '删除后无法恢复，确定删除？',
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			onOk() {
				let item = array[index]
				array.splice(index, 1)
				if (conflictRoomList.value.includes(item.id)) {
					let indexs = conflictRoomList.value.findIndex(o => o === item.id)
					if (indexs !== -1) {
						conflictRoomList.value.splice(indexs, 1)
					}
				}
			}
		})
	}

	const onDateChange = (dates: string[]) => {
		dates = dates || []
		if (props.reletId) {
			entity.endTime = dates[1]
		} else {
			entity.beginTime = dates[0]
			entity.endTime = dates[1]
		}
	}

	const quickSelectDate = () => {
		let beginDate = dayjs(entity.beginTime || nowDate())
		let endDate = beginDate.add(entity.leasePeriod || 12, 'month')

		if (beginDate.date() <= endDate.endOf('day').date()) {
			endDate = endDate.subtract(1, 'day')
		}

		entity.beginTime = beginDate.format(DATE_FORMAT.DATE)
		const endTime = endDate.format(DATE_FORMAT.DATE)

		// 判断结束日期是否在周期内
		let begin = currentTeamwork.value.beginTime
		let end = currentTeamwork.value.endTime
		if (endTime >= begin && endTime <= end) {
			entity.endTime = endTime
		} else {
			entity.leasePeriod = leasePeriod.value
			message.warn('结束日期不在合作周期内！')
		}
	}

	// 提交合同信息预览账单
	const submit = () => {
		if (checkHouseBasePrice()) {
			form.value
				?.validate()
				.then(async () => {
					if (!entity.endTime) {
						message.warn('合同周期结束日期不能为空')
						return
					}
					if (!entity.enterPriseContractHouseRoomFroms?.length) {
						message.warn('请选择房间')
						return
					}

					// 补签 换房接口不需要
					if (!entity.costPaymentConfigs?.length && (props.supplementaryId === null || props.isEnterPriseExchange)) {
						message.warn('请完善费用支付配置')
						return
					}

					if (contractDecision.value.delivery) {
						if (
							(entity.enterPriseContractHouseRoomFroms || []).filter(i => !i.isSure).length >= 1 &&
							!props.resubmitId &&
							!props.reletId
						) {
							message.warn('请确认完物业交割单')
							return
						}
					}
					if (contractDecision.value.contractNo && !entity.contractNo) {
						message.warn('请输入合同编号')
						return
					}
					// 82308字典修改

					if (await isDisabledF()) return
					if (conflictRoomList.value.length) {
						conflictRoomNameList.value = entity.enterPriseContractHouseRoomFroms.filter(e =>
							conflictRoomList.value.includes(e.id)
						)
						open.value = true
						return
					}
					// 换房不检验
					if (!props.resubmitId && entity.signType !== 2 && entity.signType !== 4) {
						validateHouseStatusF({
							ids: entity.enterPriseContractHouseRoomFroms.map(e => e.id),
							beginTime: entity.beginTime,
							endTime: entity.beginTime
						})
					} else {
						visibles.billPreview = true
					}
				})
				.catch(({errorFields}: any) => {
					form.value?.scrollToField(errorFields[0].name, {
						behavior: 'smooth'
					})
				})
		}
	}

	const getHouseMap = () => {
		const houseMap = {}
		entity.enterPriseContractHouseRoomFroms.forEach(o => (houseMap[o.id] = o))
		return houseMap
	}

	// 选择房间回显 and 周期 折扣 租金 押金
	const onSubmitSuccess = (houseList?: any[]) => {
		// console.log('🚀 ~ file: charter-sign.vue:1200 ~ onSubmitSuccess ~ data:', houseList)
		if (houseList) {
			// 获取之前的房间
			const houseMap = getHouseMap()

			// 这里对选择后的房间做处理 原来的房间配置了物业交割单会被替换掉 如果新选择的包含了原来的数据 则使用原来的数据
			houseList.forEach(house => {
				if (houseMap[house.id]) {
					XEUtils.assign(house, houseMap[house.id])
				}
			})

			entity.enterPriseContractHouseRoomFroms = houseList
		}

		//计算优惠价格
		discountCalculate()
		//查询选择房间周期是否与业主合同周期冲突
		getHouseDate()
		handleSetPropertyFee()
	}

	const onSubmitCost = (data: any) => {
		entity.costPaymentConfigs = data
	}

	//续租才需要从新下发授权
	const onSubmitBill = (type: any = 1) => {
		// 成功关闭弹窗
		onCancel()

		emits('success', type)
	}

	// 监听 员工id 维护人和签约人合并
	watchEffect(() => {
		if (entity.signEmpId) {
			entity.maintainerId = entity.signEmpId
		}
	})

	// 获取企业信息详情
	const enterpriseInformation = (data: any) => {
		const res = data.find((e: any) => e.id === props.id)
		entity.enterPriseId = res.id
		selectEnterPriseId(res.id)
	}

	// 续租 重置 等页面内容回显
	const contractDetails = async () => {
		getEnterContractDetails((props.reletId as string) || props.resubmitId || props.supplementaryId || exchangeId.value).then(
			async ({data}: any) => {
				oldDate.value.beginTime = data.beginTime
				oldDate.value.endTime = data.endTime

				// TODO 续签等操作需要判断企业是否有效，不能直接从企业列表匹配
				const enterpriseData = options.enterpriseList.find((e: any) => e.id === data.enterPriseDTO.id)

				options.teamworks = enterpriseData.teamworks
				options.contacts = enterpriseData.contacts

				if (props.resubmitId) {
					entity.id = props.resubmitId
				}

				entity.enterPriseId = enterpriseData.id
				entity.enterPriseContractId = data.id
				entity.signEmpId = data.signEmpId
				entity.signDeptId = data.signDeptId

				entity.societyCode = enterpriseData.societyCode

				entity.enterPriseUserId = data?.enterPriseUserId
				entity.enterPriseTeamWorkId = data.enterPriseTeamworkId

				entity.renterInfo = data?.renterInfoDTO

				entity.renterInfo.interest = data.renterInfoDTO?.interest ? data.renterInfoDTO?.interest : []
				entity.renterInfo.gender = data.enterPriseDTO?.gender
				entity.renterInfo.employer = data.enterPriseDTO?.enterPriseName

				selectWorkId(entity.enterPriseTeamWorkId)
				selectPriseUser(entity.enterPriseUserId)

				//合同相关
				entity.contractNo = data.contractNo
				// visibles.beginData = data.endTime
				if (props.reletId && !props.resubmitId) {
					//续租
					entity.signType = 2
					entity.beginTime = dayjs(data.endTime).add(1, 'day').format(DATE_FORMAT.DATE)
					entity.endTime = dayjs(data.endTime)
						.add(entity.leasePeriod || 6, 'month')
						.format(DATE_FORMAT.DATE)
					const time = currentTeamwork.value.endTime
					if (entity.endTime > time) {
						entity.endTime = time
					}
				}
				if (props.reletId && props.resubmitId) {
					entity.signType = 2
					entity.beginTime = data.beginTime
					entity.endTime = data.endTime
				}
				// 回显加收费用
				entity.otherExpenses = JSON.parse(data.otherExpenses || '[]')
				entity.addExplanation = data.addExplanation
				// 付款方式
				entity.depositMonth = data.depositMonth
				entity.periodMonth = data.periodMonth
				// 收租日设置
				entity.payPatternValue = data.payPatternValue
				entity.payPattern = data.payPattern

				// 补签
				if (props.supplementaryId) {
					entity.beginTime = data.beginTime
					entity.endTime = data.endTime

					entity.signType = 5
					if (!props.resubmitId) {
						entity.enterContractPid = props.supplementaryId
					}
				}

				// 换房
				if (props.isEnterPriseExchange && props.contract) {
					entity.beginTime = dayjs(props.contract.quiteDate).add(1, 'day').format(DATE_FORMAT.DATE)
					entity.endTime = props.contract.endTime
				}

				// 补签非重新提交 换房 不需要旧房间数据,租金等相关数据
				if ((props.supplementaryId || props.isEnterPriseExchange) && !props.resubmitId) {
					supplementaryBeginTime.value = dayjs(data.beginTime).format(DATE_FORMAT.DATE)
					oldHouseList.value = data.houseRoomDTOList.length
					return
				}
				const validateDeposit = contractDecision.value.disabledeposit

				// 用这个接口查询完整的房间费用明细详情 再把房间费用详情填到enterPriseContractHouseRoomFroms中
				const roomRes = await searchRoomCostDetail({
					ids: data.houseRoomDTOList?.map(i => i.id),
					houseType: 0,
					current: 1,
					size: 1000
				})
				const roomList = roomRes.data?.records || []
				entity.enterPriseContractHouseRoomFroms = data.houseRoomDTOList.map((e: any) => {
					return {
						...e,
						contractId: e.contractId,
						id: e.id,
						communityId: e?.communityId,
						deposit: e.pastDeposit || 0,
						houseId: e.id,
						housePid: e.id,
						houseAddress: e.address,
						houseType: e?.houseType,
						price: e.actualPrice || 0,
						basePrice: e.basePrice || 0,
						discountPrice: e.actualPrice || 0,
						houseRoomTypeDeposit: validateDeposit ? e.depositPrice : e.actualPrice,
						houseArea: e.houseArea || 0,
						houseRoomTypeName: e.houseRoomTypeName,
						totalFloor: e.totalFloor,
						currentFloor: e.currentFloor,
						isExamine: e.isExamine,
						signConfig: roomList.find(p => p.id === e.id)?.signConfig
					}
				})

				// 包租合同批量续租
				if (props.reletIds.length) {
					await getHouseRoomList()
				}

				// 如果是补签的重新提交 过滤房间 isExamine = 1 才需要
				if (props.supplementaryId && props.resubmitId) {
					oldHouseList.value = data.houseRoomDTOList.filter(e => e.isExamine !== 1).length
					entity.enterPriseContractHouseRoomFroms = entity.enterPriseContractHouseRoomFroms.filter(e => e.isExamine === 1)
				}

				// 审批重新提交
				//续租需要回显物业交割单 换房重新提交不需要
				if ((props.resubmitId && !props.isEnterPriseExchange) || props.reletId) {
					// entity.signType = 1
					// entity.beginTime = data.beginTime
					// entity.endTime = data.endTime
					// 重新提交要把物业交割单回填进去并且删掉ID
					entity.enterPriseContractHouseRoomFroms.forEach(async (i, index) => {
						const {data: currContractDeliver} = await getHouseDeliveryGetNoe({
							id: i.contractId,
							type: 1
						})
						console.log(currContractDeliver, 'currContractDeliver')

						if (currContractDeliver) {
							if (currContractDeliver.id) delete currContractDeliver.id
							entity.enterPriseContractHouseRoomFroms[index].deliveryAddForm = {...currContractDeliver}
							if (props.reletId || props.supplementaryId) {
								deliveryNoteList.value.push(currContractDeliver)
							}
						}
					})
				}
				//查询选择房间周期是否与业主合同周期冲突
				getHouseDate()
				//重新计算一遍押金金额
				discountCalculate()
			}
		)
	}

	//重新提交回显附件
	const attachmentF = () => {
		fileApi.getFileList(props.resubmitId || props.contract.id).then(({data}: {data: Img[]}) => {
			attachments.value = data.map(o => {
				o.name = o.fileOriginName
				return o
			})
			// 附件列表
			entity.attachmentIds = attachments.value.map(o => o.id) as []
		})
	}

	// 费用配置回显
	const getDisposeF = () => {
		getDispose((props.resubmitId as string) || (props.reletId as string) || props.supplementaryId || exchangeId.value).then(
			(res: any) => {
				// bills.value = res.data
				entity.costPaymentConfigs = res.data
			}
		)
	}

	//选择联系人
	const selectPriseUser = (value?: string | null) => {
		// 未传值取首选联系人，无首选联系人取第一个
		const defaultContact = options.contacts.find(o => o.isFirstChoice) || {}

		// 拿到的是id
		const contact = options.contacts.find(o => o.id === value) || defaultContact

		entity.enterPriseUserId = contact.id

		entity.renterInfo.name = contact?.linkmanName
		entity.renterInfo.phone = contact?.linkmanPhone
		entity.renterInfo.identityCard = contact?.linkmanIdCard
		entity.renterInfo.linkmanPost = contact?.linkmanPost
	}

	//前置房源判断
	const validateHouseStatusF = (data: any) => {
		OccupationRoomsList.value = []
		validateHouseStatus(data).then(async (res: any) => {
			if (!res.data.length) {
				// 82308字典修改
				if (await isDisabledF()) return
				visibles.billPreview = true
			} else {
				OccupationRoomsList.value = res.data
			}
		})
	}

	/** disabled判断 */
	const isDisabled = (type = 'default') => {
		let result = false
		result =
			props.id !== '' ||
			props.reletId !== null ||
			props.resubmitId !== null ||
			props.supplementaryId !== null ||
			props.isEnterPriseExchange

		if (type === 'enterPriseTeamWorkId') {
			result = entity.signType === 2 || props.supplementaryId !== null || props.isEnterPriseExchange
		}

		if (type === '续签和补签和换房') {
			result = entity.signType === 2 || props.supplementaryId !== null || props.isEnterPriseExchange
		}

		if (type === 'supplementaryId' || type === 'enterPriseUserId') {
			result = props.supplementaryId !== null || props.isEnterPriseExchange
		}

		if (type === 'enterPriseTeamworkDiscountId') {
			result = props.supplementaryId !== null
			if (entity.enterPriseTeamworkDiscountId === null) {
				result = false
			}

			// 换房和补签，不锁定优惠方案
			if (props.supplementaryId !== null || props.isEnterPriseExchange) {
				result = false
			}

			// 组件清除操作
			// console.log('清除操作====', data, entity.enterPriseTeamworkDiscountId)
			let data = options.discount.find(e => e.id === oldOnterPriseTeamworkDiscountId.value)
			if (data === undefined && entity.enterPriseTeamworkDiscountId === undefined) {
				result = false
			}
		}

		return result
	}

	/** 获取决策合同设置 */
	const getContractDecision = () => {
		settingApi.getDecisionList({module: 'CONTRACT'}).then(({data}) => {
			const mustField = data.find(o => o.mark === 'ENTERPRISE_FIELD_MUST_SETTING') || {value: '[]'}
			const belowBase = data.find(o => o.mark === 'ENTERPRISE_BELOW_BASE_PRICE') || {onOff: '1'}
			const management_fee = data.find(e => e.mark === 'MANAGEMENT_FEE_AUTO_GENERATE')
			const deposit_auto = data.find(e => e.mark === 'CONTRACT_DEPOSIT_GENERATE')

			let source = JSON.parse(mustField.value || '[]')
			contractDecision.value.delivery = source.includes(1)
			contractDecision.value.contractNo = source.includes(2)

			isAllowBasePrice.value = belowBase.onOff === '1'

			// 物业费生成配置
			let management_fee_source = JSON.parse(management_fee.value || '[]')
			contractDecision.value.shiftPropertyType = management_fee_source
			contractDecision.value.shiftProperty = management_fee.onOff === '1'
			// 合同押金生成配置
			let deposit_auto_source = JSON.parse(deposit_auto.value || '[]')
			contractDecision.value.disabledeposit = deposit_auto_source === 2 ? true : false
			contractDecision.value.depositType = deposit_auto_source
		})
	}

	const changeDate = date => {
		if (date) {
			entity.beginTime = date[0]
			entity.endTime = date[1]
			if (!date[1]) {
				entity.leasePeriod = null
			}
		}
	}

	/**
	 * 优惠计算
	 */
	const discountCalculate = () => {
		entity.enterPriseContractHouseRoomFroms.forEach(item => {
			// 每月押金基础，根据决策取
			item.depositMonthPrice = contractDecision.value.disabledeposit ? item.houseRoomTypeDeposit : item.price

			// 自定义优惠取手动输入的金额，或初始化
			if (isCustomDiscount.value) {
				item.discountPrice = item.discountPrice || item.price

				// 无自定义押金优惠权限，押金优惠金额取原始金额
				if (store.hasPermissions('mk_contract_charter_yjyhj')) {
					item.discountDeposit = item.discountDeposit || item.deposit
				} else {
					item.discountDeposit = item.deposit
				}
			} else {
				item.discountPrice = item.price
				item.discountDeposit = item.depositMonthPrice
			}
		})

		// 仅计算每月折优惠
		const discounts: any[] = options.discount.filter(o => entity.discountIds.includes(o.id) && o.discountType === 1)

		// 按优惠力度排序，优惠力度越高越前
		discounts.sort((a, b) => a.discountScale - b.discountScale)

		// console.log('当前选择优惠', toRaw(discounts))

		discounts.forEach(discount => {
			// 优惠费用范围
			const feeTags = discount.feeSubjects.map(o => o.tag)

			// console.log(
			// 	discount.discountName,
			// 	discount.feeSubjects.map(o => o.name)
			// )

			entity.enterPriseContractHouseRoomFroms.forEach(house => {
				house.discountPrice = house.discountPrice || house.price
				house.discountDeposit = house.discountDeposit || house.deposit

				// 租金
				if (feeTags.includes(DIC_TAG_MAP['HOUSE_RENT'])) {
					// console.log('租金优惠计算')
					house.discountPrice = XEUtils.multiply(house.discountPrice, discount.discountScale / 100)
				}

				// 押金
				if (feeTags.includes(DIC_TAG_MAP['HOUSE_DEPOSIT'])) {
					// console.log('押金优惠计算')
					house.discountDeposit = XEUtils.multiply(house.discountDeposit, discount.discountScale / 100)
				}
			})
		})
		// 计算完优惠后再更新实际押金
		entity.enterPriseContractHouseRoomFroms.forEach(item => {
			item.deposit = XEUtils.round(XEUtils.multiply(item.discountDeposit, entity.depositMonth || 0), 2)
		})

		checkHouseBasePrice()
	}

	// 校验房源底价
	const checkHouseBasePrice = () => {
		if (!isAllowBasePrice.value) {
			const blewBasePrice = entity.enterPriseContractHouseRoomFroms.some(o => o.discountPrice < o.basePrice)

			if (blewBasePrice) {
				message.error('优惠后价格不可低于底价，请您更改优惠方式后再次签约')
				return false
			}
		}

		return true
	}

	// 循环获取房间列表
	const getHouseRoomList = async () => {
		entity.enterPriseContractHouseRoomFroms = []
		console.log('🚀 ~ file: charter-sign.vue:1547 ~ getHouseRoomList ~ props.reletIds:', props.reletIds)

		await getEnterContractDetails(props.reletId).then(async res => {
			const {houseRoomDTOList} =res.data
			const roomRes = await searchRoomCostDetail({
				ids: props.reletIds.map(i => i.houseId),
				houseType: 0,
				current: 1,
				size: 1000
			})
			const roomList = roomRes.data?.records.map(e=>{
				const current = houseRoomDTOList.find(i=>i.id === e.id) || {}
				return {
					...current,
					...e
				}
			}) || []

			let hasError = false

			let renterContractIds: any = []
			let house = roomList.map((e: any) => {
				const validateDeposit = contractDecision.value.disabledeposit
				const validateRes = validateFee(contractDecision, e)
				if (!validateRes) hasError = true

				// 续租新增加的子合同id数组
				renterContractIds.push(e.renterContractId)

				return {
					...e,
					houseRoomTypeDeposit: validateDeposit ? e.depositPrice : e.actualPrice,
					contractId: e.contractId || e.renterContractId,
					id: e.id,
					communityId: e?.communityId,
					deposit: e.pastDeposit || 0,
					houseId: e.id,
					housePid: e.id,
					houseAddress: e.address,
					houseType: e?.houseType,
					price: e.actualPrice || 0,
					basePrice: e.basePrice || 0,
					discountPrice: e.actualPrice || 0,
					discountDeposit: e.deposit || 0,
					houseArea: e.houseArea || 0,
					houseRoomTypeName: e.houseRoomTypeName,
					totalFloor: e.totalFloor,
					currentFloor: e.currentFloor,
					isExamine: e.isExamine,
					signConfig: e.signConfig
				}
			})

			if(hasError) return

			entity.renterContractIds = renterContractIds
			console.log('🚀 ~ file: charter-sign.vue:1572 ~ house ~ house:', house)
			entity.enterPriseContractHouseRoomFroms = entity.enterPriseContractHouseRoomFroms.concat(house)
			discountCalculate()
		})
		console.log(
			'🚀 ~ file: charter-sign.vue:1575 ~ getHouseRoomList ~ entity.enterPriseContractHouseRoomFroms:',
			entity.enterPriseContractHouseRoomFroms
		)
	}

	const toFixedTwo = num => {
		return XEUtils.commafy(num, {digits: 2})
	}
	// 预计首期租金
	const expectedRent = computed(() => {
		const countPrice = XEUtils.sum(entity.enterPriseContractHouseRoomFroms, 'discountPrice')
		const rangeTime = [entity.beginTime, entity.endTime].filter(i => i)
		/** 如果选择一次性付就是 房间合计的金额 x 合作周期的大致月份 六个月过一天按照七个月算 */
		if (99 === entity.periodMonth) {
			if (2 === rangeTime.length) {
				// 获取差异天数
				const getDiffDays = dayjs(entity.endTime).diff(entity.beginTime, 'day')
				// 获取大致月份
				const monthNum = Math.ceil(getDiffDays / 31)
				return toFixedTwo(countPrice * monthNum)
			} else {
				return 0
			}
		} else {
			/** 如果选择的不是一次性支付 需要判断付几 是否大于合作周期 如果大于 按照合作周期的月份计算 */
			/** 比如合作周期选择的月份是2023-8-23 --> 2023-9-23 这时候选择付12的话 一样按照一个月去计算 */
			if (2 === rangeTime.length) {
				// 获取差异天数
				const getDiffMonth = Math.ceil(dayjs(entity.endTime).diff(entity.beginTime, 'day') / 31)
				// 获取大致月份
				const monthNum = (entity.periodMonth || 1) > getDiffMonth ? getDiffMonth : entity.periodMonth || 1
				return toFixedTwo(countPrice * monthNum)
			} else {
				return toFixedTwo(countPrice * (entity.periodMonth || 1))
			}
		}
	})
	// 预计首期押金
	const expectedDeposit = computed(() => {
		// 自定义或者续租的时候需要*押金月数
		const countDeposit = XEUtils.sum(entity.enterPriseContractHouseRoomFroms, 'deposit')
		return XEUtils.commafy(countDeposit, {digits: 2})
	})
	// 计算单条或者多条加收费用
	/**
	 * @params type 1 计算单条 2 计算多条
	 */
	const countSignOtherFee = (row: any, type: number) => {
		const rangeTime = [entity.beginTime, entity.endTime].filter(i => i)
		if (1 === type) {
			let periodMonth = row.periodMonth || 1
			/**
			 * @periodMonth
			 * 如果是随房租付-100：金额 * 付款方式的付几(如果付几大于了合作周期 则取合作周期的时间) * 房间数
			 *
			 * 如果是一次性付清-99：金额 * 1 * 房间数
			 *
			 * 如果是其他支付 [判断周期是否小于付款方式的付几 小于的话用 (周期 / 加收费用的付几) 不然就 * 1] * 房间数
			 */

			let allPrice = (row.price || 0) * (entity.enterPriseContractHouseRoomFroms?.length || 0)
			if (row.Feedisabled) {
				allPrice = row.price
			}
			if (99 === row.periodMonth) {
				periodMonth = 1
				return periodMonth * allPrice
			} else if (100 === row.periodMonth) {
				if (2 === rangeTime.length) {
					// 获取差异天数
					const getDiffDays = dayjs(entity.endTime).diff(entity.beginTime, 'day')
					// 获取大致月份
					const getMonth = Math.ceil(getDiffDays / 31)
					const entityPeriodMonth = entity.periodMonth || 1
					periodMonth = getMonth < entityPeriodMonth ? getMonth : entityPeriodMonth
					return periodMonth * allPrice
				} else {
					return 0
				}
			} else {
				if (2 === rangeTime.length) {
					// 获取差异天数
					const getDiffDays = dayjs(entity.endTime).diff(entity.beginTime, 'day')
					// 获取大致月份
					const getMonth = Math.ceil(getDiffDays / 31)
					periodMonth = getMonth < row.periodMonth ? getMonth : row.periodMonth
				} else {
					periodMonth = 1
				}
				return periodMonth * allPrice
			}
		} else {
			const countOtherFee = (entity.otherExpenses || []).reduce((prev, curr) => {
				return prev + (countSignOtherFee(curr, 1) || 0)
			}, 0)
			return countOtherFee
		}
	}
	// 预计其他费用
	const expectedOtherFee = computed(() => {
		return toFixedTwo(countSignOtherFee({}, 2))
	})
	/* 判断选择的字典是否被禁用 */
	// / 82308字典修改
	const isDisabledF = async () => {
		let temp = false
		let typesList: any = []
		let list: any = []
		let otherExpenses: any = XEUtils.clone(entity.otherExpenses, true)
		typesList = await settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT'], {isUse: 1})
		typesList.data.forEach((e: any) => {
			list.push(...e.metaList)
		})

		list.forEach((e: any) => {
			otherExpenses?.forEach((o: any) => {
				if (e.id == o.feeSubjectId) {
					o.active = true
				}
				if (o.Feedisabled === true) {
					o.active = true
				}
			})
		})

		if (!otherExpenses?.every((e: any) => e?.active == true)) {
			temp = true
			return message.error('选项已禁用，请选择其他选项！')
		}
		return temp
	}

	const batchModal = reactive({
		visible: false,
		name: '',
		value: null,
		key: null,
		show(key) {
			batchModal.value = null
			batchModal.key = key
			batchModal.name = {
				'discountPrice': '租金',
				'discountDeposit': '押金'
			}[key]
			batchModal.visible = true
		},
		ok() {
			if (!batchModal.value) {
				return message.error('请输入批量修改价')
			}
			entity.enterPriseContractHouseRoomFroms.forEach(room => {
				if (batchModal.key === 'discountPrice') {
					if (!isAllowBasePrice.value && batchModal.value < room.basePrice) {
						message.error('优惠价格不可低于底价，请重新输入')
						return
					}
				}
				room[batchModal.key] = batchModal.value
			})
			batchModal.visible = false
			discountCalculate()
		}
	})
</script>

<style lang="less">
	.add-charter {
		.ant-modal-body {
			padding: 0 16px;
			overflow: auto;
			min-height: 600px;
			max-height: 1000px;
			height: calc(100vh - 200px);

			.ant-form-item {
				margin-bottom: 16px;

				label[for='form_item_beginTime'] {
					display: flex;

					.display-flex {
						flex: 1;
						justify-content: space-around;
					}
				}
			}

			.custom-radio-group {
				.ant-space {
					display: flex;

					.ant-space-item {
						flex: 1;
					}
				}

				.ant-radio-button-wrapper {
					height: 96px;
					display: block;

					.ant-typography {
						margin-bottom: 6px;
					}
				}
			}

			.template-select-wrapper {
				.ant-form-item-control {
					flex-direction: row;
					align-items: center;
					gap: 16px;

					.ant-select-selection-search {
						left: 0;
					}

					.ant-form-item-extra {
						color: @warning-color;
						font-size: @font-size-sm;
					}
				}

				.ant-select {
					width: 160px;

					.ant-select-selector {
						padding: 0;
						font-size: @font-size-sm;
					}
				}
			}

			.month-quick-radio-group {
				.ant-radio-button-wrapper {
					padding: 0 9px;
				}
			}

			.ant-input-number-group-addon {
				background: #fff;
				color: @text-color;
			}

			.edit-table-row {
				.ant-input,
				.ant-select-selector {
					padding: 0;
					border: none;
				}

				.ant-select,
				.ant-input-number {
					width: 100%;
				}

				.ant-radio-wrapper:last-child {
					margin-right: 0;
				}
			}
		}
	}

	.toolbar-color-blockquote {
		strong {
			display: flex;
			justify-content: space-between;
		}
	}

	.add-expected-other-fee {
		.t-l {
			text-align: left;
		}
	}
	.row-red {
		border-color: red;
	}
	.batch-edit-input {
		width: 140px;
	}
	.batch-edit-input .ant-input-number-group-addon {
		padding: 0;
	}
	.batch-edit-btn {
		font-size: 12px;
		line-height: 22px;
		padding: 0 12px;
		cursor: pointer;
		background-color: #0266ff;
		height: 22px;
		color: white;
	}
</style>
